package com.hlyj.http.base.tool.lib_hlyj_base.bean;

import android.os.Build;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    // AES密钥算法
    private static final String KEY_ALGORITHM = "AES";

    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    // 生成密钥
//    public static String generateAESKey() throws Exception {
//        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
//        keyGenerator.init(128, new SecureRandom()); // 192 and 256 bits may not be available
//        SecretKey secretKey = keyGenerator.generateKey();
//        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
//    }

    // 加密
    public static String encryptAES(String data, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        }
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Base64.getEncoder().encodeToString(encrypted);
        }
        return null;
    }

    // 解密
//    public static String decryptAES(String data, String key) throws Exception {
//        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
//        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
//        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
//        return new String(decrypted);
//    }


    /**
     * 将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String byte2ParseHex(byte buf[]) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuffer.append(hex.toUpperCase());
        }
        return stringBuffer.toString();
    }


    /**
     * 将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] hexParseByte2(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;

    }


}
